package com.lin.service.MulThread;

import cn.hutool.core.util.RandomUtil;

import java.util.Random;
import java.util.concurrent.Semaphore;

public class SemaphoreCase {
    public static void main(String[] args) {
        Runnable customer = new Runnable() {
            Semaphore availableTable = new Semaphore(5, true);
            int count = 1;
            @Override
            public void run() {
                int time = RandomUtil.randomInt(1, 10);
                int num = count++;
                try {
                    availableTable.acquire();
                    System.out.println("第【" + num + "】个用户正在用餐，需要时间：" + time + "s！");
                    Thread.sleep(time * 1000);
                    //释放锁
                    availableTable.release();
                    //判断是否有线程正在等待
                    if (availableTable.hasQueuedThreads()) {
                        System.out.println("第【" + num + "】个客户已用餐完毕，有请下一位！，目前有空闲桌位有【"+availableTable.availablePermits()+"】桌");
                    } else {
                        System.out.println("第【" + num + "】个客户已用餐完毕，目前有空闲桌位有【"+availableTable.availablePermits()+"】桌");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        for (int i = 1; i < 10; i++) {
            new Thread(customer).start();
        }
    }
}
